import * as YUKA from "./yuka.module.js";
import * as THREE from "../libs/three.module.js";
import * as DAT from "../libs/dat.gui.module.js";
import { FBXLoader } from "./FBXLoader.js";
import { OrbitControls } from "../build/OrbitControls.js";
// import {
//     createSphereHelper,
//     createAABBHelper,
//     createOBBHelper,
//     createConvexHullHelper,
// } from './BVHelper.js';
CameraControls.install({ THREE: THREE });
var Options = function () {
  this.message = "dat.gui";
  this.simulation_bh = 1;
  this.displayOutline = false;
  this.button = false;
};

window.onload = function () {
  var options = new Options();
  var gui = new DAT.GUI({ name: "操作控制" });

  var controller = gui
    .add(
      options,
      "simulation_bh",
      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
    )
    .name("工况选择");
  // gui.add(options, "displayOutline").name("显示路径");
  // gui.add(options, "button").name("显示框体");
  controller.onChange(function (value) {
    console.log("onChange:" + value);
    simulation_bh = value - 1;
    // timePlayer.slider('refresh', {
    //     min: minDate.getTime(),
    //     max: maxDate.getTime(),
    //     useCurrentValue: true,
    // });
    minDate = simulationInfo[value - 1].start_time;
    maxDate = simulationInfo[value - 1].end_time;
    initTime({
      curTime: simulationInfo[value - 1].start_time,
      minTime: simulationInfo[value - 1].start_time,
      maxTime: simulationInfo[value - 1].end_time,
    });
    clearScene();
  });
};
let mixer, pcjModel, zdjModel;
var timePlayer = null;
var opt = [];

var simulation_bh = 0;
//var biAddress = 'http://210.42.37.102:3000/api/';
var biAddress = "http://localhost:3000/api/";
var minDate = new Date("2022-04-01 00:09:50.000");
var maxDate = new Date("2022-04-04 00:44:21.000");
var pcjSize = [4.3, 1.9, 2.8];
var zdjSize = [5.8, 3.0, 4.4];
const points = [];
var currentTimeObject = new Date();
const counterDOM = document.getElementById("counter");
const cavas = document.getElementById("cavas");
const indexDoM = document.getElementById("span");
const endDOM = document.getElementById("end");
const controllsDOM = document.getElementById("controlls");
var timePlayerDOM = document.getElementById("ibv-timeplayer");
var yukahelper;
let duringTimeAnimate = false;
let isAnimate = false;
console.log(
  window.innerWidth / -2,
  window.innerWidth / 4,
  window.innerHeight / 4,
  window.innerHeight / -2
);
//创建场景
const scene = new THREE.Scene();
const simulationInfo = [
  {
    simulation_bh: 1,
    start_time: "2022-04-01T00:03:25.830Z",
    end_time: "2022-04-01T00:41:41.017Z",
    warehouseid: 1,
    stripid: 1,
    bz: "正常1-1(2个卸料点，3min卸料周期)",
  },
  {
    simulation_bh: 2,
    start_time: "2022-04-01T12:09:43.943Z",
    end_time: "2022-04-01T12:48:36.020Z",
    warehouseid: 1,
    stripid: 2,
    bz: "正常1-2(2个卸料点，3min卸料周期)",
  },
  {
    simulation_bh: 3,
    start_time: "2022-04-01T18:05:43.787Z",
    end_time: "2022-04-01T18:44:39.080Z",
    warehouseid: 2,
    stripid: 3,
    bz: "正常2-1(2个卸料点，3min卸料周期)",
  },
  {
    simulation_bh: 4,
    start_time: "2022-04-01T18:50:06.663Z",
    end_time: "2022-04-01T19:28:25.013Z",
    warehouseid: 2,
    stripid: 4,
    bz: "正常2-2(2个卸料点，3min卸料周期)",
  },
  {
    simulation_bh: 5,
    start_time: "2022-04-01T20:32:28.460Z",
    end_time: "2022-04-01T21:10:35.043Z",
    warehouseid: 3,
    stripid: 5,
    bz: "正常3-1(2个卸料点，3min卸料周期)",
  },
  {
    simulation_bh: 6,
    start_time: "2022-04-01T21:15:08.020Z",
    end_time: "2022-04-01T21:53:53.017Z",
    warehouseid: 3,
    stripid: 6,
    bz: "正常3-2(2个卸料点，3min卸料周期)",
  },
  {
    simulation_bh: 7,
    start_time: "2022-04-01T22:05:09.163Z",
    end_time: "2022-04-01T22:44:28.053Z",
    warehouseid: 1,
    stripid: 1,
    bz: "正常1-1(5个卸料点)",
  },
  {
    simulation_bh: 8,
    start_time: "2022-04-02T18:45:00.307Z",
    end_time: "2022-04-02T20:12:08.037Z",
    warehouseid: 1,
    stripid: 1,
    bz: "正常1-1(5个卸料点，7min卸料周期)",
  },
  {
    simulation_bh: 9,
    start_time: "2022-04-02T22:10:49.667Z",
    end_time: "2022-04-02T23:37:31.023Z",
    warehouseid: 1,
    stripid: 1,
    bz: "正常1-1(2个卸料点，7min卸料周期)",
  },
  {
    simulation_bh: 10,
    start_time: "2022-04-03T10:44:16.070Z",
    end_time: "2022-04-03T12:11:14.017Z",
    warehouseid: 1,
    stripid: 2,
    bz: "正常1-2(2个卸料点，7min卸料周期)",
  },
  {
    simulation_bh: 11,
    start_time: "2022-04-03T13:57:02.433Z",
    end_time: "2022-04-03T15:22:56.030Z",
    warehouseid: 2,
    stripid: 3,
    bz: "正常2-1(2个卸料点，7min卸料周期)",
  },
  {
    simulation_bh: 12,
    start_time: "2022-04-03T15:30:55.710Z",
    end_time: "2022-04-03T16:57:48.027Z",
    warehouseid: 2,
    stripid: 4,
    bz: "正常2-2(2个卸料点，7min卸料周期)",
  },
  {
    simulation_bh: 13,
    start_time: "2022-04-03T18:32:31.177Z",
    end_time: "2022-04-03T19:59:22.017Z",
    warehouseid: 3,
    stripid: 5,
    bz: "正常3-1(2个卸料点，7min卸料周期)",
  },
  {
    simulation_bh: 14,
    start_time: "2022-04-03T20:04:30.760Z",
    end_time: "2022-04-03T21:31:32.020Z",
    warehouseid: 3,
    stripid: 6,
    bz: "正常3-2(2个卸料点，7min卸料周期)",
  },
  {
    simulation_bh: 15,
    start_time: "2022-04-05T12:27:36.617Z",
    end_time: "2022-04-05T13:54:21.020Z",
    warehouseid: 1,
    stripid: 1,
    bz: "正常1-1(2个卸料点，7min卸料周期，增加预测数据)",
  },
  {
    simulation_bh: 15,
    start_time: "2022-04-24 23:07:06.000",
    end_time: "2022-04-25 00:30:55.000",
    warehouseid: 1,
    stripid: 1,
    bz: "正常1-1(2个卸料点，7min卸料周期，增加预测数据)",
  },
];
const distance = 500;
const positionWidth = 30; //单点的位置宽度
const columns = 54; //一共有多少列\
const rows = 24; //一共有多少列
const boardWidth = positionWidth * columns; //横向长度范围
const boardHeight = positionWidth * rows;

function initLine(x) {
  const material = new THREE.LineBasicMaterial({ color: 0xffffff });
  const points = [];
  points.push(new THREE.Vector3(x * positionWidth, 0, 0));
  points.push(new THREE.Vector3(x * positionWidth, 24 * positionWidth, 0));
  const geometry = new THREE.BufferGeometry().setFromPoints(points);
  //geometry.vertices.push(new THREE.Vector3(10, 0, 0));
  const line = new THREE.Line(geometry, material);
  scene.add(line);
}
function initPlane() {
  const geometry = new THREE.PlaneGeometry(boardWidth, boardHeight, 54, 24);
  const material = new THREE.MeshBasicMaterial({
    color: 0x454a59,
    side: THREE.DoubleSide,
  });
  const plane = new THREE.Mesh(geometry, material);
  plane.position.x = boardWidth / 2;
  plane.position.y = boardHeight / 2;
  plane.position.z = 0;

  scene.add(plane);
}
function drawTile(point, color) {
  console.log("point", point, color);
  const geometry = new THREE.PlaneGeometry(
    9 * positionWidth,
    boardHeight,
    54,
    24
  );
  const material = new THREE.MeshBasicMaterial({
    color: color,
    side: THREE.DoubleSide,
  });
  const plane = new THREE.Mesh(geometry, material);
  plane.position.x = point * 9 * positionWidth + (9 * positionWidth) / 2;
  plane.position.y = boardHeight / 2;
  plane.position.z = 1;
  plane.name = point;
  scene.add(plane);
}

function drawConflict(record) {
  for (let i = 0; i < 6; i++) {
    let isojb = scene.getChildByName(i);
    if (isojb) {
      scene.remove(isojb);
    }
  }
  if (record && record.length > 0) {
    for (let i = 0; i < record.length; i++) {
      let temp = record[i];
      temp.pti =
        temp.per_p != null && temp.per_p != "-"
          ? parseFloat(temp.per_p.replace("%", "")) / 100
          : 0;
      temp.sti =
        temp.per_s != null && temp.per_s != "-"
          ? parseFloat(temp.per_s.replace("%", "")) / 100
          : 0;
      temp.eti =
        temp.per_e != null && temp.per_e != "-"
          ? parseFloat(temp.per_e.replace("%", "")) / 100
          : 0;
      if (temp.pti > 0) {
        drawTile(temp.stripid - 1, "red");
      } else if (temp.sti > 0.301 || temp.eti > 0.363) {
        drawTile(temp.stripid - 1, "yellow");
      }
    }
  }
}

const offsetx = window.innerWidth / 2 - boardWidth / 2;
const offsety = window.innerHeight / 2 - boardHeight / 2;

const camera = new THREE.PerspectiveCamera(
  90,
  window.innerWidth / window.innerHeight,
  1,
  10000
);
//camera.rotation.x = 50 * Math.PI / 180;
camera.rotation.x = 0;
//camera.rotation.y = 20 * Math.PI / 180;
//camera.rotation.z = 10 * Math.PI / 180;
camera.rotation.y = 0;
const initialCameraPositionY = -Math.tan(camera.rotation.x) * distance;
const initialCameraPositionX =
  Math.tan(camera.rotation.y) *
  Math.sqrt(distance ** 2 + initialCameraPositionY ** 2);
camera.position.y = boardHeight / 2;
camera.position.x = boardWidth / 2;
camera.position.z = 800;

const helper = new THREE.CameraHelper(camera);
//scene.add(helper);
const zoom = 2;
let index = 0;
let indexTwo = 0;
let indexThree = 0;
const chickenSize = 15;

const stepTime = 200; // Miliseconds it takes for the chicken to take a step forward, backward, left or right

const TileOne = [
  [4.5, 8],
  [4.5, 16],
  [13.5, 8],
  [13.5, 16],
];
const TileTwo = [
  [22.5, 8],
  [22.5, 16],
  [31.5, 8],
  [31.5, 16],
];
const TileThree = [
  [40.5, 8],
  [40.5, 16],
  [49.5, 8],
  [49.5, 16],
];

let stepStartTimestamp;

const chicken = new Chicken();
const chickenThree = new Chicken();
const chickenTwo = new Chicken();
const pcjOne = await PcjInstance("./model/pingcangji1.FBX");
const pcjTwo = await PcjInstance("./model/pingcangji1.FBX");
const pcjThree = await PcjInstance("./model/pingcangji1.FBX");
const viborOne = await zdjInstance("./model/zhendaoji1.FBX");
const viborTwo = await zdjInstance("./model/zhendaoji1.FBX");
const viborThree = await zdjInstance("./model/zhendaoji1.FBX");
const boxArray = {
  pcjOne,
  pcjTwo,
  pcjThree,
  viborOne,
  viborTwo,
  viborThree,
  tileApcj: createPolygon(pcjSize, Math.PI),
  tileBpcj: createPolygon(pcjSize, Math.PI),
  tileCpcj: createPolygon(pcjSize, Math.PI),
  tileAzdj: createPolygon(zdjSize, 0),
  tileBzdj: createPolygon(zdjSize, 0),
  tileCzdj: createPolygon(zdjSize, 0),
};

const clearScene = () => {
  for (let value of Object.values(boxArray)) {
    console.log("value", value);
    value.visible = false;
  }
  for (let key of ["pone", "ptwo", "pthree"].values()) {
    let path = scene.getChildByName(key);
    if (path) {
      scene.remove(path);
    }
  }
};
var loader = new FBXLoader();
const initaliseValues = () => {
  //lanes = generateLanes()
  initPlane();
  initLine(9);
  initLine(18);
  initLine(27);
  initLine(36);
  initLine(45);
  scene.add(chicken);
  scene.add(chickenTwo);
  scene.add(chickenThree);
  scene.add(pcjOne);
  scene.add(pcjTwo);
  scene.add(pcjThree);
  scene.add(viborOne);
  scene.add(viborTwo);
  scene.add(viborThree);
  pcjOne.visible = false;
  pcjTwo.visible = false;
  pcjThree.visible = false;
  viborOne.visible = false;
  viborTwo.visible = false;
  viborThree.visible = false;
  chicken.position.x = 4.5 * positionWidth;
  chicken.position.y = 8 * positionWidth;
  chickenTwo.position.x = (4.5 + 18) * positionWidth;
  chickenTwo.position.y = 8 * positionWidth;
  chickenThree.position.x = (4.5 + 36) * positionWidth;
  chickenThree.position.y = 8 * positionWidth;
};

const renderer = new THREE.WebGLRenderer({
  alpha: true,
  antialias: true,
});
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setSize(window.innerWidth, window.innerHeight);
cavas.appendChild(renderer.domElement);

const hemiLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.6);
scene.add(hemiLight);

const clock = new THREE.Clock(); //用于更新轨道控制器

const dirLight = new THREE.DirectionalLight(0xffffff, 0.6);
dirLight.position.set(-100, -100, 200);
dirLight.castShadow = true;
scene.add(dirLight);

dirLight.shadow.mapSize.width = 2048;
dirLight.shadow.mapSize.height = 2048;
var d = 500;
dirLight.shadow.camera.left = -d;
dirLight.shadow.camera.right = d;
dirLight.shadow.camera.top = d;
dirLight.shadow.camera.bottom = -d;

const backLight = new THREE.DirectionalLight(0x000000, 0.4);
backLight.position.set(200, 200, 50);
backLight.castShadow = true;
scene.add(backLight);

initaliseValues();
initEdge();
//drawLine();
let time = new YUKA.Time();

console.log("points=>>2", points);

//const controls = new OrbitControls(camera, renderer.domElement);
const cameraControls = new CameraControls(camera, renderer.domElement);
cameraControls.setOrbitPoint(boardWidth / 2, boardHeight / 2, 0);
//controls.target = new THREE.Vector3(0, 0, 0);
//controls.autoRotate = false; //将自动旋转关闭
//controls.update();

function drawLine(sX, sY, eX, eY, name) {
  //create a blue LineBasicMaterial
  let lineOpt = {
    color: 0xffffff,
    linewidth: 1,
    scale: 1,
    dashSize: 10,
    gapSize: 5,
  };

  const material = new THREE.LineDashedMaterial(lineOpt);
  const geometry = new THREE.BufferGeometry();

  const pointsArray = new Array();
  pointsArray.push(
    new THREE.Vector3(sX * positionWidth, sY * positionWidth, 10)
  );
  pointsArray.push(
    new THREE.Vector3(eX * positionWidth, eY * positionWidth, 10)
  );
  geometry.setFromPoints(pointsArray);
  //geometry.computeLineDistances();
  const line = new THREE.Line(geometry, material);
  line.computeLineDistances();
  let isojb = scene.getChildByName(name);
  if (isojb) {
    scene.remove(isojb);
  }
  line.name = name;
  scene.add(line);
}
function Chicken() {
  const chicken = new THREE.Group();
  const cylinder = new THREE.Mesh(
    new THREE.CylinderGeometry(0, 60, 50, 50, 50, false),
    new THREE.MeshPhongMaterial({ color: "gray", flatShading: true })
  );

  const body = new THREE.Mesh(
    new THREE.BoxBufferGeometry(
      chickenSize * zoom,
      chickenSize * zoom,
      20 * zoom
    ),
    new THREE.MeshPhongMaterial({ color: 0xffffff, flatShading: true })
  );
  body.position.z = 10 * zoom;
  body.castShadow = true;
  body.receiveShadow = true;
  //chicken.add(body);
  chicken.add(cylinder);
  chicken.rotation.x = Math.PI / 2;
  chicken.position.z = 25;
  const rowel = new THREE.Mesh(
    new THREE.BoxBufferGeometry(2 * zoom, 4 * zoom, 2 * zoom),
    new THREE.MeshLambertMaterial({ color: 0xf0619a, flatShading: true })
  );
  rowel.position.z = 21 * zoom;
  rowel.castShadow = true;
  rowel.receiveShadow = false;
  //chicken.add(rowel);

  return chicken;
}

function returnFBX(PATH) {
  const loader = new FBXLoader();
  return new Promise((resolved, rejected) => {
    console.log("async task begins!");
    loader.load(PATH, function (object) {
      resolved(object);
    });
  });
}

function computeZX(item) {
  // if (item.ys_x === 0) {
  //     //振捣机
  //     return {
  //         x: (item.zs_x + zdjSize[0] / 2) * positionWidth,
  //         y: (item.zs_y - zdjSize[1] / 2) * positionWidth,
  //     };
  // }
  const zxPoint = {
    x: ((item.zs_x + item.yx_x) * positionWidth) / 2,
    y: ((item.zs_y + item.yx_y) * positionWidth) / 2,
  };
  return zxPoint;
}
function computeZdjZX(item) {
  // if (item.ys_x === 0) {
  //     //振捣机
  //     return {
  //         x: (item.zs_x + zdjSize[0] / 2) * positionWidth,
  //         y: (item.zs_y - zdjSize[1] / 2) * positionWidth,
  //     };
  // }
  const zxPoint = {
    x: ((item.Zs_x + item.Yx_x) * positionWidth) / 2,
    y: ((item.Zs_y + item.Yx_y) * positionWidth) / 2,
  };
  return zxPoint;
}

function computerRota(item) {
  const adiff = item.ys_x - item.zs_x;
  const bdiff = item.ys_y - item.zs_y;
  let rotationDegree = (Math.atan(adiff / bdiff) * 180) / Math.PI;
  if (bdiff < 0) {
    rotationDegree += 180;

    // Adjust for 4th quadrant
    // i.e. diff x is -ve, diff y is +ve
  } else if (adiff < 0) {
    rotationDegree += 360;
  }
  return rotationDegree;
}

function computerRotation(sX, sY, eX, eY) {
  let dRotateAngle = Math.atan2(Math.abs(sX - eX), Math.abs(sY - eY));

  if (eX > sX || eX === sX) {
    //第一和第四象限
    if (eY > sY || eY === sY) {
      //第一象限
      dRotateAngle = dRotateAngle;
    } else {
      //第四象限
      dRotateAngle = Math.PI - dRotateAngle;
    }
  } else if (eX < sX) {
    if (eY > sY || eY === sY) {
      //第二象限
      dRotateAngle = 2 * Math.PI - dRotateAngle;
    } else {
      //第三象限
      dRotateAngle = Math.PI + dRotateAngle;
    }
  }

  const adiff = sX - eX;
  const bdiff = sY - eY;
  if (bdiff === 0) {
    //竖线时
    dRotateAngle = Math.PI / 2;
  } else if (adiff === 0) {
    //横线
    dRotateAngle = 0;
  }

  return dRotateAngle;
}

function createPolygon(size, degree) {
  const group = new THREE.Group();

  const geometry2 = new THREE.BoxGeometry(
    size[0] * positionWidth + 20,
    size[1] * positionWidth + 10,
    size[2] * positionWidth + 10
  );

  var wireframeMaterial = new THREE.MeshBasicMaterial({
    color: 0x000000,
    wireframe: true,
    transparent: true,
  });
  var mesh2 = new THREE.Mesh(geometry2, wireframeMaterial);
  group.rotation.x = degree;
  group.add(mesh2);
  group.position.z = 30;
  return group;
}

function moveTile(opt, obj, tileArray, tileA, tileB) {
  const { pureid, stripid } = opt;
  console.log("pureid, stripid", pureid, stripid);
  if (pureid <= 6 && stripid === tileA) {
    const temp = tileArray[0];
    obj.position.x = temp[0] * positionWidth;
    obj.position.y = temp[1] * positionWidth;
  } else if (pureid > 6 && stripid === tileA) {
    const temp = tileArray[1];
    obj.position.x = temp[0] * positionWidth;
    obj.position.y = temp[1] * positionWidth;
  } else if (pureid <= 6 && stripid === tileB) {
    const temp = tileArray[2];
    obj.position.x = temp[0] * positionWidth;
    obj.position.y = temp[1] * positionWidth;
  } else if (pureid > 6 && stripid === tileB) {
    const temp = tileArray[3];
    obj.position.x = temp[0] * positionWidth;
    obj.position.y = temp[1] * positionWidth;
  }
}

function drawPath(opt, name, box) {
  const { pureid, stripid, stepid, scraperID } = opt;
  $.ajax({
    type: "get",
    async: true,
    url:
      biAddress +
      "routepath/" +
      simulation_bh +
      "/" +
      scraperID +
      "/" +
      pureid +
      "/" +
      stripid +
      "/" +
      stepid,
    dataType: "json",
    success: function (data) {
      //let { cdict, sensors } = initSensors(data.recordset);
      console.log("path", data);
      const { sX, sY, eX, eY } = data.recordset[0];
      drawLine(sX, sY, eX, eY, name);

      if (name === "pone") {
        if (pcjOne.rotation.z !== 0) {
          console.log("当前的旋转角度", pcjOne.rotation.z);
          pcjOne.rotation.z = 0;
        }

        let temp = computerRotation(sX, sY, eX, eY);

        console.log("计算的角度", temp);
        pcjOne.rotation.z = temp + Math.PI / 2;
        box.rotation.z = temp + Math.PI / 2;
        console.log("旋转后的角度", pcjOne);
      } else if (name === "ptwo") {
        if (pcjTwo.rotation.z !== 0) {
          console.log("当前的旋转角度", pcjOne.rotation.z);
          pcjTwo.rotation.z = 0;
        }
        let temp = computerRotation(sX, sY, eX, eY);
        pcjTwo.rotation.z = temp + Math.PI / 2;
        box.rotation.z = temp + Math.PI / 2;
        console.log("旋转后的角度", pcjTwo);
      } else {
        if (pcjThree.rotation.z !== 0) {
          console.log("当前的旋转角度", pcjOne.rotation.z);
          pcjThree.rotation.z = 0;
        }
        let temp = computerRotation(sX, sY, eX, eY);
        pcjThree.rotation.z = temp + Math.PI / 2;
        box.rotation.z = temp + Math.PI / 2;
        console.log("旋转后的角度", pcjThree);
      }
    },
  });
}
function getPre(bh) {
  $.ajax({
    type: "get",
    async: true,
    url: biAddress + "/getCsmPre/" + bh,
    dataType: "json",
    success: function (data) {
      console.log("getCsmPre", data);
      window.parent &&
        window.parent.postMessage(
          { type: "csmPre", data: data.recordset },
          "*"
        );
    },
  });
}
function drawBox(opt) {
  const coordOne = opt.filter((item) => item.scraperID === 1);
  console.log("zxPointOne", coordOne, opt);
  if (coordOne && coordOne.length > 0) {
    const zxPointOne = computeZX(coordOne[0]);

    pcjOne.position.x = zxPointOne.x;
    pcjOne.position.y = zxPointOne.y;
    pcjOne.visible = true;
    //let temp = computerRota(coordOne[0]);
    //console.log("temp", temp);
    //pcjOne.rotation.z = temp;
    const box = boxArray.tileApcj;
    scene.add(box);
    box.position.x = zxPointOne.x;
    box.position.y = zxPointOne.y;
    //box.rotation.z = temp;
    box.visible = true;
    moveTile(coordOne[0], chicken, TileOne, 1, 2);
    drawPath(coordOne[0], "pone", box);
    if (simulation_bh > 13) {
      getPre(coordOne[0].mxxh);
    }
  }
  const coordTwo = opt.filter((item) => item.scraperID === 2);
  if (coordTwo && coordTwo.length > 0) {
    const zxPointTwo = computeZX(coordTwo[0]);
    pcjTwo.position.x = zxPointTwo.x;
    pcjTwo.position.y = zxPointTwo.y;
    pcjTwo.visible = true;
    // let temp = computerRota(coordTwo[0]);
    // pcjTwo.rotation.z = temp;
    const box = boxArray.tileBpcj;
    scene.add(box);
    box.position.x = zxPointTwo.x;
    box.position.y = zxPointTwo.y;
    //box.rotation.z = temp;
    box.visible = true;
    moveTile(coordTwo[0], chickenTwo, TileTwo, 3, 4);
    drawPath(coordTwo[0], "ptwo", box);
    if (simulation_bh > 13) {
      getPre(coordTwo[0].mxxh);
    }
  }
  const coordThree = opt.filter((item) => item.scraperID === 3);
  if (coordThree && coordThree.length > 0) {
    const zxPointThree = computeZX(coordThree[0]);
    pcjThree.position.x = zxPointThree.x;
    pcjThree.position.y = zxPointThree.y;
    pcjThree.visible = true;
    // let temp = computerRota(coordThree[0]);
    // pcjThree.rotation.z = temp;
    const box = boxArray.tileCpcj;
    scene.add(box);
    box.position.x = zxPointThree.x;
    box.position.y = zxPointThree.y;
    // box.rotation.z = temp;
    box.visible = true;
    moveTile(coordThree[0], chickenThree, TileThree, 5, 6);
    drawPath(coordThree[0], "pthree", box);
    if (simulation_bh > 13) {
      getPre(coordThree[0].mxxh);
    }
  }
  // const aabb = new YUKA.AABB().fromPoints(points);
  // if (yukahelper) {
  //     scene.remove(yukahelper);
  // }
  // yukahelper = createAABBHelper(aabb);
  // yukahelper.position.x = model.position.x;
  // yukahelper.position.y = model.position.y;
  // yukahelper.position.z = 30;
  // scene.add(yukahelper);
}
function drawCvmBox(opt) {
  const coordOne = opt.filter((item) => item.VibratorID === 1);

  if (coordOne && coordOne.length > 0) {
    const zxPointOne = computeZdjZX(coordOne[0]);
    viborOne.position.x = zxPointOne.x;
    viborOne.position.y = zxPointOne.y;
    viborOne.visible = true;
    // let temp = computerRota(coordOne[0]);
    // viborOne.rotation.z = temp;
    // const box = boxArray.tileAzdj;
    // scene.add(box);
    // box.position.x = zxPointOne.x;
    // box.position.y = zxPointOne.y;
    // box.rotation.z = temp;
    // box.visible = true;
    // if (coordOne[0].yx_x != 0) {
    //     const rodegree = computerRota(coordOne[0]);
    //     viborOne.rotation.z = rodegree;
    // }
  }
  const coordTwo = opt.filter((item) => item.VibratorID === 4);

  if (coordTwo && coordTwo.length > 0) {
    console.log("zxPointTwozdj", coordTwo, opt);
    const zxPointTwo = computeZdjZX(coordTwo[0]);
    viborTwo.position.x = zxPointTwo.x;
    viborTwo.position.y = zxPointTwo.y;
    // if (coordTwo[0].yx_x != 0) {
    //     const rodegree = computerRota(coordTwo[0]);
    //     viborTwo.rotation.z = rodegree;
    // }
    viborTwo.visible = true;
  }
  const coordThree = opt.filter((item) => item.VibratorID === 7);

  if (coordThree && coordThree.length > 0) {
    console.log("zxPointThreezdj", coordThree, opt);
    const zxPointThree = computeZdjZX(coordThree[0]);
    viborThree.position.x = zxPointThree.x;
    viborThree.position.y = zxPointThree.y;
    // if (coordThree[0].yx_x != 0) {
    //     const rodegree = computerRota(coordThree[0]);
    //     viborThree.rotation.z = rodegree;
    // }
    viborThree.visible = true;
  }
}

function getAngle({ x: x1, y: y1 }, { x: x2, y: y2 }) {
  const dot = x1 * x2 + y1 * y2;
  const det = x1 * y2 - y1 * x2;
  const angle = (Math.atan2(det, dot) / Math.PI) * 180;
  return Math.round(angle + 360) % 360;
}

async function PcjInstance(PATH) {
  const chicken = new THREE.Group();
  const b = await returnFBX(PATH);
  console.log("pasdasdacj", b);
  chicken.add(b);
  chicken.rotation.x = Math.PI;
  let size = new THREE.Vector3();
  let sizeb = new THREE.Vector3();
  let avatar = {};
  b.traverse(function (child) {
    if (child.isMesh) {
      avatar = child;

      const geometry = avatar.geometry.toNonIndexed();
      //geometry.applyMatrix(avatar.matrixWorld); // bake model transformation
      const position = geometry.getAttribute("position");
      let box3 = new THREE.Box3().setFromObject(avatar);

      box3.getSize(size);
      console.log("geo size", size);
      for (let i = 0; i < position.count; i++) {
        const x = position.getX(i);
        const y = position.getY(i);
        const z = position.getZ(i);

        points.push(new YUKA.Vector3(x, y, z));
      }
    }
  });

  const aabb = new YUKA.AABB().fromPoints(points);
  const { min, max } = aabb;
  const xScale = (pcjSize[0] * positionWidth) / size.x;
  const yScale = (pcjSize[1] * positionWidth) / size.y;
  const zScale = (pcjSize[2] * positionWidth) / size.z;
  chicken.position.z = 20;
  chicken.scale.set(xScale, yScale, zScale);
  //console.log('aabb', size, xScale, yScale, zScale);
  let box3 = new THREE.Box3().setFromObject(chicken);
  box3.getSize(sizeb);
  console.log("scale size", sizeb);
  return chicken;
}

async function zdjInstance(PATH) {
  const chicken = new THREE.Group();
  const b = await returnFBX(PATH);
  //console.log('pasdasdacj', b);
  chicken.add(b);
  chicken.rotation.x = Math.PI / 2;

  let avatar = {};
  b.traverse(function (child) {
    if (child.isMesh) {
      avatar = child;
      const geometry = avatar.geometry.toNonIndexed();
      //geometry.applyMatrix(avatar.matrixWorld); // bake model transformation
      const position = geometry.getAttribute("position");

      for (let i = 0; i < position.count; i++) {
        const x = position.getX(i);
        const y = position.getY(i);
        const z = position.getZ(i);

        points.push(new YUKA.Vector3(x, y, z));
      }
    }
  });

  const aabb = new YUKA.AABB().fromPoints(points);
  const { min, max } = aabb;
  const xScale = (zdjSize[0] * positionWidth) / (max.x - min.x);
  const yScale = (zdjSize[1] * positionWidth) / (max.y - min.y);
  const zScale = (zdjSize[2] * positionWidth) / (max.z - min.z);
  chicken.position.z = 10;
  chicken.scale.set(xScale, yScale, zScale);
  console.log("aabb", aabb, xScale);

  return chicken;
}

function sync(entity, renderComponent) {
  //console.log('sync', renderComponent, entity)
  renderComponent.matrix.copy(entity.worldMatrix);
  //renderComponent.mesh.copy(entity.mesh);
}

function generateTarget(arriveObj, index, targetObj) {
  counterDOM.innerHTML = index;
  // generate a random point on a sphere
  let [x, y] = arriveObj[index];
  const carfinalx = x * positionWidth;
  const carfinaly = y * positionWidth;
  targetObj.position.x = carfinalx;
  targetObj.position.y = carfinaly;
  targetObj.position.z = 90;
}

function initEdge() {
  var geometry = new THREE.PlaneGeometry(boardWidth, 100);
  var material = new THREE.MeshBasicMaterial({
    color: 0x808080,
    side: THREE.DoubleSide,
  });
  var plane = new THREE.Mesh(geometry, material);
  plane.position.set(boardWidth / 2, 0, 0);
  plane.rotation.x = (90 * Math.PI) / 180;
  scene.add(plane);
  var geometry = new THREE.PlaneGeometry(boardWidth, 100);
  var material = new THREE.MeshBasicMaterial({
    color: 0x808080,
    side: THREE.DoubleSide,
  });
  var plane = new THREE.Mesh(geometry, material);
  plane.position.set(boardWidth / 2, boardHeight, 0);
  plane.rotation.x = (90 * Math.PI) / 180;
  scene.add(plane);
  var geometry = new THREE.PlaneGeometry(boardHeight, 100);
  var material = new THREE.MeshBasicMaterial({
    color: 0x808080,
    side: THREE.DoubleSide,
  });
  var plane = new THREE.Mesh(geometry, material);
  plane.position.set(0, boardHeight / 2, 0);
  plane.rotation.z = (90 * Math.PI) / 180;
  plane.rotation.y = (90 * Math.PI) / 180;
  scene.add(plane);
  var geometry = new THREE.PlaneGeometry(boardHeight, 100);
  var material = new THREE.MeshBasicMaterial({
    color: 0x808080,
    side: THREE.DoubleSide,
  });
  var plane = new THREE.Mesh(geometry, material);
  plane.position.set(boardWidth, boardHeight / 2, 0);
  plane.rotation.z = (90 * Math.PI) / 180;
  plane.rotation.y = (90 * Math.PI) / 180;
  scene.add(plane);
  // plane = new THREE.Mesh(geometry, material);
  // plane.rotation.y = (90 * Math.PI) / 180;
  // plane.position.set(length / 2, 5, 0);
  // scene.add(plane);
  // plane = new THREE.Mesh(geometry, material);
  // plane.position.set(0, 5, -length / 2);
  // scene.add(plane);
  // plane = new THREE.Mesh(geometry, material);
  //
  // plane.position.set(-length / 2, 5, 0);
  // scene.add(plane);
}

function atTarget(vehicleobj, target) {
  return vehicleobj.position.squaredDistanceTo(target.position) < positionWidth;
}
function animate() {
  requestAnimationFrame(animate);

  const delta = time.update().getDelta();

  //entityManager.update(delta);
  //console.log('arriveBehavior', yukavehicle.getSpeed())
  // if (atTarget(yukavehicle, target)) {
  //     generateTarget(pcjCoordinate, index, target);
  //     // generateTarget(viCoorOne, index, targetFour);
  //     if (index < 144) {
  //         if (index % 72 === 0) {
  //             let temp = index / 72;
  //             let [a, b] = TileOne[temp];
  //             MoveTile(chicken, a, b);
  //         }
  //         index++;
  //     } else {
  //         index = 0;
  //     }
  // }
  // if (atTarget(yukavehicleTwo, targetTwo)) {
  //     generateTarget(pcjCoordinateTwo, indexTwo, targetTwo);
  //     generateTarget(viCoorTwo, indexTwo, targetFive);
  //     if (indexTwo < 144) {
  //         if (indexTwo % 72 === 0) {
  //             let temp = indexTwo / 72;
  //             let [a, b] = TileTwo[temp];
  //             MoveTile(chicken2, a, b);
  //         }
  //         indexTwo++;
  //     } else {
  //         indexTwo = 0;
  //     }
  // }
  // if (atTarget(yukavehicleThree, targetThree)) {
  //     generateTarget(pcjCoordinateThree, indexThree, targetThree);
  //     generateTarget(viCoorThree, indexThree, targetSix);
  //     if (indexThree < 144) {
  //         if (indexThree % 72 === 0) {
  //             let temp = indexThree / 72;
  //             let [a, b] = TileThree[temp];
  //             MoveTile(chicken3, a, b);
  //         }
  //         indexThree++;
  //     } else {
  //         indexThree = 0;
  //     }
  // }
  const updated = cameraControls.update(delta);
  //controls.update(delta);
  renderer.render(scene, camera);
}
//requestAnimationFrame(animate);

function showTimer() {
  $("#ibv-timeplayer-timer").pietimer(
    {
      seconds: 3,
      color: "rgba(255,255,255,255)",
      height: 20,
      width: 20,
    },
    function () {}
  );
  $("#ibv-timeplayer-timer").pietimer("start");
}

function timeChange(timeObject) {
  opt = [];
  let second = timeObject.getTime();
  $.ajax({
    type: "get",
    async: true,
    url: biAddress + "/csmDetail/" + second,
    dataType: "json",
    success: function (data) {
      //let { cdict, sensors } = initSensors(data.recordset);

      console.log("record", data);

      opt = opt.concat(data.recordset);
      window.parent &&
        window.parent.postMessage({ type: "csm", data: data.recordset }, "*");
      var $table = $("#table");
      $table.bootstrapTable("load", opt);
      // const
      // //console.log('load data', coordinate[0]);
      // pcjOne.position.x = coordinate[0].zx_x * positionWidth;
      // pcjOne.position.y = coordinate[0].zx_y * positionWidth;
      drawBox(opt);
    },
  });
  console.log("second", second);
  $.ajax({
    type: "get",
    async: true,
    url: biAddress + "/cvmDetail/" + second,
    dataType: "json",
    success: function (data) {
      //let { cdict, sensors } = initSensors(data.recordset);
      //var $table = $('#table');
      console.log("record", data);
      const coors = data.recordset;

      drawCvmBox(coors);
      opt = opt.concat(data.recordset);
      window.parent &&
        window.parent.postMessage({ type: "cvm", data: data.recordset }, "*");
      var $table = $("#table");
      $table.bootstrapTable("load", opt);
      //opt = opt.join(coors);

      //opt = data.recordset;
      // const
      // //console.log('load data', coordinate[0]);
      // pcjOne.position.x = coordinate[0].zx_x * positionWidth;
      // pcjOne.position.y = coordinate[0].zx_y * positionWidth;
      //drawCvmBox(opt);
      //$table.bootstrapTable('load', opt);
    },
  });
  $.ajax({
    type: "get",
    async: true,
    url: biAddress + "/conflict/" + second,
    dataType: "json",
    success: function (data) {
      //let { cdict, sensors } = initSensors(data.recordset);
      //var $table = $('#table');
      console.log("record", data);
      drawConflict(data.recordset);
      window.parent &&
        window.parent.postMessage(
          { type: "cresult", data: data.recordset },
          "*"
        );
    },
  });

  console.log("scene", scene);
}

// function updateRange(event) {
//   try {
//     // if (timePlayer) {
//     //     try {
//     //         timePlayer.slider('destroy');
//     //     } catch (e) {}
//     // } else {
//     try {
//       timePlayer.slider("destroy");
//     } catch (e) {}
//     //点击播放
//     $("#ibv-timeplayer-play").click(function () {
//       try {
//         console.log("playclick", isAnimate, duringTimeAnimate);
//         var min = minDate.getTime();
//         var max = maxDate.getTime();

//         if (duringTimeAnimate) {
//           clearInterval(isAnimate);
//           duringTimeAnimate = false;
//           timePlayer.slider("enable");
//           showTimer();
//         } else {
//           if (isAnimate) {
//             clearInterval(isAnimate);
//             duringTimeAnimate = false;
//           }
//           timePlayer.slider("disable");
//           duringTimeAnimate = true;
//           isAnimate = setInterval(function () {
//             if (timePlayer.slider("getValue") < max) {
//               timePlayer.slider(
//                 "setValue",
//                 timePlayer.slider("getValue") + 1000,
//                 true,
//                 true
//               );
//             } else {
//               clearInterval(isAnimate);
//               duringTimeAnimate = false;
//               timePlayer.slider("enable");
//               showTimer();
//             }
//           }, 100);
//         }
//       } catch (e) {
//         console.log("error", e);
//       }
//     });

//     //点击加速
//     $("#ibv-timeplayer-speedup").click(function () {
//       if (speed >= maxSpeed) {
//         speed = maxSpeed;
//       } else {
//         speed++;
//       }
//       $("#ibv-timeplayer-speedtext").html("x" + Math.pow(2, speed));
//     });

//     //点击减速
//     $("#ibv-timeplayer-speeddown").click(function () {
//       if (speed <= minSpeed) {
//         speed = minSpeed;
//       } else {
//         speed--;
//       }
//       $("#ibv-timeplayer-speedtext").html("x" + Math.pow(2, speed));
//     });
//     if (event.hideSlider) {
//       $("#ibv-timeplayer").hide();
//     } else {
//       //计算时间范围
//       let { minTime, maxTime, curTime } = event.detail;
//       var curDate = new Date();
//       if (minTime) {
//         minDate = new Date(minTime);
//       }
//       //var minDate = new Date('2017-03-16 06:46:00');

//       if (maxTime) {
//         maxDate = new Date(maxTime);
//       }
//       if (curTime) {
//         curDate = new Date(curTime);
//       }

//       var step = 10000;
//       var speed = 0;
//       var animate = null;
//       var maxSpeed = 5;
//       var minSpeed = 0;
//       var range = maxDate.getTime() - minDate.getTime();

//       //初始化时间节点
//       var nodeArray = [];
//       var nodeTextArray = [];
//       var nodePositionArray = [];
//       nodeArray.push(minDate.getTime());
//       nodeArray.push(maxDate.getTime());
//       nodeTextArray.push(minDate.toLocaleDateString());
//       nodeTextArray.push(maxDate.toLocaleDateString());
//       nodePositionArray.push(0);

//       var nodeSize = 6;
//       var monthStep = Math.ceil(
//         (maxDate.getTime() - minDate.getTime()) / (step * 30) / nodeSize
//       );

//       var tempDate = new Date();
//       tempDate.setTime(minDate.getTime());

//       while (maxDate.getTime() - tempDate.getTime() > step) {
//         tempDate.setMilliseconds(100000);
//         //console.log("min max", minDate.getTime(), maxDate.getTime(), range);
//         if (tempDate <= maxDate) {
//           //nodeTextArray.push(tempDate.toLocaleTimeString());
//           nodePositionArray.push(
//             ((tempDate.getTime() - minDate.getTime()) / range) * 100
//           );
//         }
//       }

//       $("#ibv-timeplayer").show();

//       //初始化时间控件
//       timePlayer = $("#ibv-timeplayer-slider")
//         .slider({
//           min: minDate.getTime(),
//           max: maxDate.getTime(),
//           ticks: nodeArray,
//           ticks_labels: nodeTextArray,
//           //ticks_positions: nodePositionArray,
//           value: curDate.getTime(),
//           tooltip: "always",
//           step: step,
//           formatter: function (value) {
//             var date = new Date();
//             date.setTime(value);
//             return date.toLocaleDateString();
//           },
//         })
//         .on("change", function (e) {
//           //analyseView.setHistoryTime(new Date(e.value.newValue));
//           console.log("e", e);
//           //selectTime =new Date(e.value.newValue);
//           let selectTime = new Date(e.value.newValue);
//           //console.log('e.value.newValue', e.value.newValue);
//           //hntview.timeChange(new Date(e.value));
//           timeChange(selectTime);
//           initTime({ curTime: selectTime });
//           //console.log('second', second, opt);
//         });
//       $("#ex1Slider").css({
//         width: window.innerWidth - 500 + "px",
//       });
//     }
//     // }
//   } catch (e) {
//     console.warn(e.message);
//   }
// }
var animateIns;

function updateRange(event) {
  try {
    console.log("timeplayder", timePlayer);
    if (timePlayer) {
      try {
        timePlayer.slider("destroy");
        $("#ibv-timeplayer-play").unbind("click");
      } catch (e) {}
    } else {
      //点击播放

      //点击加速
      $("#ibv-timeplayer-speedup").click(function () {
        if (speed >= maxSpeed) {
          speed = maxSpeed;
        } else {
          speed++;
        }
        $("#ibv-timeplayer-speedtext").html("x" + Math.pow(2, speed));
      });

      //点击减速
      $("#ibv-timeplayer-speeddown").click(function () {
        if (speed <= minSpeed) {
          speed = minSpeed;
        } else {
          speed--;
        }
        $("#ibv-timeplayer-speedtext").html("x" + Math.pow(2, speed));
      });
    }

    if (event.hideSlider) {
      $("#ibv-timeplayer").hide();
    } else {
      //计算时间范围
      console.log("slider event", event.detail);
      const { minTime, maxTime, curTime } = event.detail;
      $("#ibv-timeplayer-play").click(function () {
        try {
          console.log("play event", event.detail);
          const { minTime, maxTime, curTime } = event.detail;
          var max = new Date(maxTime);
          if (duringTimeAnimate) {
            clearInterval(animateIns);
            duringTimeAnimate = false;
            timePlayer.slider("enable");
            showTimer();
          } else {
            if (animateIns) {
              clearInterval(animateIns);
              duringTimeAnimate = false;
            }
            timePlayer.slider("disable");
            duringTimeAnimate = true;
            animateIns = setInterval(function () {
              if (timePlayer.slider("getValue") < max.getTime()) {
                timePlayer.slider(
                  "setValue",
                  timePlayer.slider("getValue") + step,
                  true,
                  true
                );
                timeChange(new Date(timePlayer.slider("getValue")));
              } else {
                clearInterval(animate);
                duringTimeAnimate = false;
                timePlayer.slider("enable");
                showTimer();
              }
            }, 300);
          }
        } catch (e) {}
      });
      var minDate;
      if (minTime) {
        minDate = new Date(minTime);
      }

      var maxDate;
      if (maxTime) {
        maxDate = new Date(maxTime);
      } else {
        maxDate = new Date();
      }
      if (curTime) {
        currentTimeObject = new Date(curTime);
      }
      var step = 1000;
      var speed = 0;
      var animate = null;
      var maxSpeed = 5;
      var minSpeed = 0;
      var range = maxDate.getTime() - minDate.getTime();

      //初始化时间节点
      var nodeArray = [];
      var nodeTextArray = [];
      var nodePositionArray = [];
      nodeArray.push(minDate.getTime());
      nodeArray.push(maxDate.getTime());
      nodeTextArray.push(minDate.toString());
      nodeTextArray.push(maxDate.toString());
      nodePositionArray.push(0);
      nodePositionArray.push(100);

      $("#ibv-timeplayer").show();

      //初始化时间控件
      timePlayer = $("#ibv-timeplayer-slider")
        .slider({
          min: minDate.getTime(),
          max: maxDate.getTime(),
          ticks: nodeArray,
          ticks_labels: nodeTextArray,
          ticks_positions: nodePositionArray,
          value: currentTimeObject.getTime(),
          tooltip: "always",
          step: step,
          formatter: function (value) {
            var date = new Date();
            date.setTime(value);
            return date.toLocaleDateString();
          },
        })
        .on("slideStop", function (e) {
          // analyseView.setHistoryTime(new Date(e.value.newValue));
          // if (updateTemprStateTimeout) {
          //   clearTimeout(updateTemprStateTimeout);
          //   updateTemprStateTimeout = null;
          // }
          // updateTemprStateTimeout = setTimeout(function () {
          //   updateTemprStateTimeout = null;

          //   hntView.timerEvent();
          //   gjgjView.timerEvent();
          //   bpView.timerEvent();
          // }, 3000);
          // if (!analyseView.duringTimeAnimate) {
          //   showTimer();
          // }
          console.log("e", e);
          currentTimeObject = new Date(e.value);
          timeChange(currentTimeObject);
        });
      $("#ex1Slider").css({ width: window.innerWidth - 500 + "px" });
    }
  } catch (e) {
    console.warn(e.message);
  }
}
function initTime(detail) {
  var event = new CustomEvent("onTimePlayerNeedUpdateRange", {
    detail,
  });
  timePlayerDOM.dispatchEvent(event);
}

function initTable(tabledata) {
  var $table = $("#table");
  var data = [];
  $(function () {
    if (tabledata) {
      data = [
        {
          microstep_time: "2021-12-03T12:50:00.000Z",
          mxxh: 45,
          pureid: 1,
          scraperID: 1,
          stepid: 3,
          stripid: 7,
          warehouseid: 2,
          ys_x: 3.03,
          ys_y: 6.64,
          yx_x: 3.34,
          yx_y: 10.93,
          zs_x: 4.93,
          zs_y: 6.5,
          zx_x: 5.24,
          zx_y: 10.79,
        },
      ];
      data = tabledata;
    } else {
      console.log("set data", data);
      $table.bootstrapTable({ data: data });
    }
  });
}
timePlayerDOM.addEventListener("onTimePlayerNeedUpdateRange", updateRange);
initTime({
  curTime: simulationInfo[simulation_bh].start_time,
  minTime: simulationInfo[simulation_bh].start_time,
  maxTime: simulationInfo[simulation_bh].end_time,
});
initTable();

animate();
